<?php

/**
 * Adding a Contact
 * @package ModuleGestionContacts
 * @version 1.0b
 */

session_start();

// Configuration file
include '../configuration.php';
// Functions
include '../inc/functions.php';

// Checking if user is logged in
if (!CheckSession()):
	exit();
endif;

// Include all objects
// TODO: Include only needed classes
foreach (glob($configuration['webroot'].'objects/*.php') as $class) { include_once $class; }

try {
	// Format purposes
	$date = '';
	if (strlen($_POST['birthdate']) > 0):
		$date = explode('/', $_POST['birthdate']);
		$date = $date[2].'-'.$date[1].'-'.$date[0];
	endif;
	
	// Creating contact
	$contact = new Contact();
	$contact->salutation = $_POST['salutation'];
	$contact->lastname = ucwords(strtolower($_POST['lastname']));
	$contact->firstname = ucwords(strtolower($_POST['firstname']));
	$contact->birthdate = $date;
	$contact->jobtitle = $_POST['jobtitle'];
	$contact->email = $_POST['email'];
	
	if (!empty($_POST['ad_street'])):
		$address = new Address();
		$address->name = $_POST['ad_name'];
		$address->building = $_POST['ad_building'];
		$address->city = $_POST['ad_city'];
		$address->number = $_POST['ad_number'];
		$address->postalcode = $_POST['ad_postalcode'];
		$address->street = $_POST['ad_street'];
		$address->type = 'MAINADDRESS';
		
		$address->Save();
		$list = Array($address);
		$contact->SetAddressList($list);
	endif;
	
	// Inserting contact into database
	$contact->SaveNew();
	
	echo 'OK';
	
} catch (Exception $e) {
	echo $e->getMessage();
}
?>